package cn.itsource.pethome.system.service.impl;

import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.system.domain.Menu;
import cn.itsource.pethome.system.mapper.MenuMapper;
import cn.itsource.pethome.system.service.IMenuService;
import cn.itsource.pethome.util.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zcj
 * @since 2022-10-19
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public void update(Menu menu) {
        if(menu.getParentId() == menu.getId()){
            throw new BusinessException("自己不能是自己的父级");
        }
        super.update(menu);
    }

    @Override
    public List<Menu> tree() {
        List<Menu> menus = menuMapper.queryAll();
        List<Menu> tree = new ArrayList<>();
        for (Menu menu : menus) {
            if(menu.getParentId() == null){
                tree.add(menu);
            }else {
                for (Menu menu1 : menus) {
                    if(menu.getParentId() == menu1.getId()){
                        menu1.getChildren().add(menu);
                    }
                }
            }
        }
        return tree;
    }
}
